import matplotlib.pyplot as plt
from scipy.stats import scoreatpercentile
import numpy as np
import csv
import random
from datetime import datetime
from time import strftime
from sympy import *

'''
revision of test24
to calculate the false nagetive, false positive

'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def fivenum(v):
    """Returns Tukey's five number summary (minimum, lower-hinge, median, upper-hinge, maximum) for the input vector, a list or array of numbers based on 1.5 times the interquartile distance"""
    import numpy as np
    from scipy.stats import scoreatpercentile
    try:
        np.sum(v)
    except TypeError:
        print('Error: you must provide a list or array of only numbers')
    q1 = scoreatpercentile(v,25)
    q3 = scoreatpercentile(v,75)
    md = np.median(v)
    return np.min(v), q1, md, q3, np.max(v),

def nullH():
    c = 6000.0
    clusterPop = [1684327, 360275, 7627173]  # original: mixed, rural, urban
    #clusterPop = [1611198, 501040, 7025156]
    
    #n = clusterPop[2]
    N = 29535210
    #k = 1.645 * ((c*n*(N-n)/(N*N))**0.5) + c*n/N
    print '#CASES = ', c
    print 'average risk = ', (c + 0.0)/totalPop
    print 'expected #cases = ', c *(N - sum(clusterPop)) / N
    print 'variance = ', c *(N - sum(clusterPop)) * sum(clusterPop) / ( N * N)
    risk = [(c + 0.0)/totalPop]
    for n in clusterPop:
        print '----------'
        print 'pop = ', n
        k = Symbol('k')
        k = solve((k-c*n/N)/((c*n*(N-n)/(N*N))**0.5) - 1.645, k)
        k = k[0]
        r = Symbol('r')
        eqn = Eq((((N - n + n * r) * k - c * n * r) ** 2)/(c * n * r * (N - n)), 3.09 ** 2)
        r = 0
        temp = solve(eqn)
        for i in temp:
            if i > 1:
                r = i
        if r > 0:
            print 'r = ', r
        else:
            print 'error in solving r'

        print 'E(c|Ha) = ', c * n * r / (N - n + n * r)
        print 'Var(c|Ha) = ', c * n * r * (N - n) / ((N - n + n * r) ** 2)
        print 'Var(c|Ha) = ', c * n * r * (N - n + n * r - c * r) / ((N - n + n * r) ** 2)
        print 'risk = ', c * r / (N - n + n * r)
        risk.append(c * r / (N - n + n * r))
    print risk

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "begin at " + getCurTime()
    
    nullH()
    
    print "end at " + getCurTime()
    print "========================================================================"  

           
